// HJQ/TemplateManagement.tsx
import React, { useState, useEffect, useCallback } from 'react';
import { 
  Card, Row, Col, Table, Button, Input, Space, 
  Modal, Form, Spin, message, Popconfirm, Select,
  Switch, Input as AntInput
} from 'antd';
import { 
  PlusOutlined, SearchOutlined, EditOutlined, 
  DeleteOutlined, EyeOutlined, SaveOutlined, 
  CloseOutlined 
} from '@ant-design/icons';
import dayjs from 'dayjs';

// 类型定义
interface HealthplanDto {
  Id: number;
  Code: string;
  Title: string;
  Keywords: string;
  Typeid: number;
  Content: string;
  State: number;
  Remark: string;
  Createtime: string;
  Updatetime: string;
}

// 模板类型选项
const templateTypes = [
  { value: 1, label: '健康计划' },
  { value: 2, label: '体检方案' },
  { value: 3, label: '康复指导' },
  { value: 4, label: '饮食建议' },
];

// 状态选项
const stateOptions = [
  { value: 0, label: '禁用', color: 'red' },
  { value: 1, label: '启用', color: 'green' },
];

// 静态模拟数据
const initialTemplates: HealthplanDto[] = [
  {
    Id: 1,
    Code: 'JH-2023001',
    Title: '基础健康体检模板',
    Keywords: '体检,基础,健康',
    Typeid: 2,
    Content: '包含一般检查、血常规、尿常规、肝功能、肾功能等基础项目',
    State: 1,
    Remark: '适用于普通人群年度体检',
    Createtime: '2023-05-10 09:30:00',
    Updatetime: '2023-05-10 09:30:00'
  },
  {
    Id: 2,
    Code: 'JH-2023002',
    Title: '老年人健康管理计划',
    Keywords: '老年人,健康管理,慢性病',
    Typeid: 1,
    Content: '针对60岁以上老人制定的健康管理方案，包含定期体检、慢性病管理等',
    State: 1,
    Remark: '需结合家庭医生随访',
    Createtime: '2023-05-12 14:20:00',
    Updatetime: '2023-06-01 16:45:00'
  },
  {
    Id: 3,
    Code: 'JH-2023003',
    Title: '术后康复指导方案',
    Keywords: '术后,康复,指导',
    Typeid: 3,
    Content: '外科手术后康复训练计划，包含活动强度、饮食建议、复查时间等',
    State: 0,
    Remark: '版本已更新，此模板停用',
    Createtime: '2023-04-25 11:10:00',
    Updatetime: '2023-05-20 10:15:00'
  },
  {
    Id: 4,
    Code: 'JH-2023004',
    Title: '糖尿病饮食建议',
    Keywords: '糖尿病,饮食,健康',
    Typeid: 4,
    Content: '针对2型糖尿病患者的饮食控制方案，包含每日热量摄入、食物选择等',
    State: 1,
    Remark: '需根据患者具体情况调整',
    Createtime: '2023-05-18 08:50:00',
    Updatetime: '2023-05-18 08:50:00'
  },
  {
    Id: 5,
    Code: 'JH-2023005',
    Title: '高血压管理模板',
    Keywords: '高血压,管理,用药',
    Typeid: 1,
    Content: '高血压患者日常管理计划，包含血压监测、用药指导、生活方式调整',
    State: 1,
    Remark: '适用于1-2级高血压患者',
    Createtime: '2023-06-02 15:30:00',
    Updatetime: '2023-06-05 11:20:00'
  }
];

const TemplateManagement: React.FC = () => {
  // 状态管理
  const [form] = Form.useForm();
  const [templates, setTemplates] = useState<HealthplanDto[]>(initialTemplates);
  const [loading, setLoading] = useState<boolean>(false);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [searchCode, setSearchCode] = useState<string>('');
  const [visible, setVisible] = useState<boolean>(false);
  const [currentTemplate, setCurrentTemplate] = useState<HealthplanDto | null>(null);
  const [isViewMode, setIsViewMode] = useState<boolean>(false);
  const [formTitle, setFormTitle] = useState<string>('新增模板');

  // 过滤后的数据源（根据搜索条件）
  const filteredTemplates = templates.filter(template => 
    template.Code.toLowerCase().includes(searchCode.toLowerCase()) ||
    template.Title.toLowerCase().includes(searchCode.toLowerCase())
  );

  // 分页处理
  const getPagedData = () => {
    const startIndex = (currentPage - 1) * pageSize;
    return filteredTemplates.slice(startIndex, startIndex + pageSize);
  };

  // 模拟获取数据（带加载状态）
  const fetchTemplates = useCallback(async () => {
    setLoading(true);
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    setLoading(false);
  }, [templates, searchCode, currentPage, pageSize]);

  // 初始化加载
  useEffect(() => {
    fetchTemplates();
  }, [fetchTemplates]);

  // 处理搜索
  const handleSearch = () => {
    setCurrentPage(1);
    fetchTemplates();
  };

  // 处理分页变化
  const handleTableChange = (pagination: any) => {
    setCurrentPage(pagination.current);
    setPageSize(pagination.pageSize);
  };

  // 显示新增模板弹窗
  const showAddModal = () => {
    setCurrentTemplate(null);
    setFormTitle('新增模板');
    setIsViewMode(false);
    form.resetFields();
    setVisible(true);
  };

  // 显示编辑模板弹窗
  const showEditModal = (record: HealthplanDto) => {
    setCurrentTemplate(record);
    setFormTitle('编辑模板');
    setIsViewMode(false);
    form.setFieldsValue({
      Code: record.Code,
      Title: record.Title,
      Keywords: record.Keywords,
      Typeid: record.Typeid,
      Content: record.Content,
      State: record.State,
      Remark: record.Remark
    });
    setVisible(true);
  };

  // 显示查看模板弹窗
  const showViewModal = (record: HealthplanDto) => {
    setCurrentTemplate(record);
    setFormTitle('查看模板');
    setIsViewMode(true);
    form.setFieldsValue({
      Code: record.Code,
      Title: record.Title,
      Keywords: record.Keywords,
      Typeid: record.Typeid,
      Content: record.Content,
      State: record.State,
      Remark: record.Remark
    });
    setVisible(true);
  };

  // 生成新ID
  const generateNewId = () => {
    return Math.max(...templates.map(t => t.Id), 0) + 1;
  };

  // 处理表单提交（新增/编辑）
  const handleFormSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 500));

      const now = dayjs().format('YYYY-MM-DD HH:mm:ss');
      
      if (currentTemplate) {
        // 编辑模板
        setTemplates(templates.map(t => 
          t.Id === currentTemplate.Id 
            ? { ...t, ...values, Updatetime: now } 
            : t
        ));
        message.success('模板更新成功');
      } else {
        // 新增模板
        const newTemplate: HealthplanDto = {
          Id: generateNewId(),
          ...values,
          Createtime: now,
          Updatetime: now
        };
        setTemplates([...templates, newTemplate]);
        message.success('模板创建成功');
      }
      
      setVisible(false);
    } catch (error) {
      console.error('提交表单失败:', error);
      message.error('提交失败，请检查输入');
    } finally {
      setLoading(false);
    }
  };

  // 处理删除模板
  const handleDelete = async (id: number) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 500));
      
      setTemplates(templates.filter(t => t.Id !== id));
      message.success('模板删除成功');
    } catch (error) {
      console.error('删除模板失败:', error);
      message.error('删除失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理状态切换
  const handleStateChange = async (id: number, currentState: number) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 300));
      
      const newState = currentState === 1 ? 0 : 1;
      setTemplates(templates.map(t => 
        t.Id === id 
          ? { ...t, State: newState, Updatetime: dayjs().format('YYYY-MM-DD HH:mm:ss') } 
          : t
      ));
      message.success(`模板已${newState === 1 ? '启用' : '禁用'}`);
    } catch (error) {
      console.error('修改状态失败:', error);
      message.error('操作失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '模板编码',
      dataIndex: 'Code',
      key: 'Code',
      width: 120,
      sorter: (a: HealthplanDto, b: HealthplanDto) => a.Code.localeCompare(b.Code)
    },
    {
      title: '模板标题',
      dataIndex: 'Title',
      key: 'Title',
      width: 200,
    },
    {
      title: '关键词',
      dataIndex: 'Keywords',
      key: 'Keywords',
      width: 150,
    },
    {
      title: '模板类型',
      dataIndex: 'Typeid',
      key: 'Typeid',
      width: 120,
      render: (typeid: number) => {
        const type = templateTypes.find(t => t.value === typeid);
        return type ? type.label : '未知';
      },
      filters: templateTypes.map(type => ({
        text: type.label,
        value: type.value,
      })),
      onFilter: (value: number, record: HealthplanDto) => record.Typeid === value,
    },
    {
      title: '状态',
      dataIndex: 'State',
      key: 'State',
      width: 100,
      render: (state: number, record: HealthplanDto) => (
        <Switch
          checked={state === 1}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          onChange={() => handleStateChange(record.Id, state)}
          style={{ 
            backgroundColor: state === 1 ? '#52c41a' : '#f5222d' 
          }}
        />
      ),
      filters: stateOptions.map(s => ({
        text: s.label,
        value: s.value,
      })),
      onFilter: (value: number, record: HealthplanDto) => record.State === value,
    },
    {
      title: '创建时间',
      dataIndex: 'Createtime',
      key: 'Createtime',
      width: 160,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm'),
      sorter: (a: HealthplanDto, b: HealthplanDto) => 
        dayjs(a.Createtime).valueOf() - dayjs(b.Createtime).valueOf()
    },
    {
      title: '更新时间',
      dataIndex: 'Updatetime',
      key: 'Updatetime',
      width: 160,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: any, record: HealthplanDto) => (
        <Space size="small">
          <Button 
            type="text" 
            icon={<EyeOutlined />} 
            onClick={() => showViewModal(record)}
            size="small"
          >
            查看
          </Button>
          <Button 
            type="text" 
            icon={<EditOutlined />} 
            onClick={() => showEditModal(record)}
            size="small"
            style={{ color: '#1890ff' }}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此模板吗？"
            onConfirm={() => handleDelete(record.Id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="text" 
              icon={<DeleteOutlined />} 
              size="small"
              style={{ color: '#f5222d' }}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px', background: '#f0f2f5', minHeight: '100vh' }}>
      {/* 页面标题和面包屑 */}
      <div style={{ marginBottom: '24px' }}>
        <div style={{ fontSize: '20px', fontWeight: 'bold', marginBottom: '8px' }}>
          模板管理
        </div>
        <div style={{ color: '#999', fontSize: '14px' }}>
          系统管理 / 模板管理
        </div>
      </div>

      {/* 筛选和操作区域 */}
      <Card style={{ marginBottom: '24px' }}>
        <Row gutter={16} align="middle">
          <Col flex="auto">
            <Space size="middle">
              <AntInput
                placeholder="请输入模板编码或标题搜索"
                value={searchCode}
                onChange={(e) => setSearchCode(e.target.value)}
                onPressEnter={handleSearch}
                style={{ width: 300 }}
                prefix={<SearchOutlined />}
              />
              <Button 
                type="primary" 
                onClick={handleSearch}
                icon={<SearchOutlined />}
              >
                搜索
              </Button>
              <Button 
                onClick={() => {
                  setSearchCode('');
                  setCurrentPage(1);
                }}
              >
                重置
              </Button>
            </Space>
          </Col>
          <Col>
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={showAddModal}
            >
              新增模板
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 模板列表表格 */}
      <Card>
        <Spin spinning={loading}>
          <Table
            columns={columns}
            dataSource={getPagedData()}
            rowKey="Id"
            pagination={{
              current: currentPage,
              pageSize: pageSize,
              total: filteredTemplates.length,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
              pageSizeOptions: ['10', '20', '50', '100'],
            }}
            onChange={handleTableChange}
            scroll={{ x: 1200 }}
            bordered
          />
        </Spin>
      </Card>

      {/* 模板表单弹窗 */}
      <Modal
        title={formTitle}
        open={visible}
        onCancel={() => setVisible(false)}
        maskClosable={false}
        footer={[
          <Button key="cancel" onClick={() => setVisible(false)} icon={<CloseOutlined />}>
            取消
          </Button>,
          !isViewMode && (
            <Button 
              key="submit" 
              type="primary" 
              onClick={handleFormSubmit}
              loading={loading}
              icon={<SaveOutlined />}
            >
              保存
            </Button>
          )
        ]}
        width={700}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ State: 1, Typeid: 1 }}
        >
          <Form.Item
            name="Code"
            label="模板编码"
            rules={[
              { required: true, message: '请输入模板编码' },
              { max: 50, message: '编码长度不能超过50个字符' }
            ]}
          >
            <AntInput placeholder="请输入模板编码" disabled={isViewMode} />
          </Form.Item>
          
          <Form.Item
            name="Title"
            label="模板标题"
            rules={[
              { required: true, message: '请输入模板标题' },
              { max: 100, message: '标题长度不能超过100个字符' }
            ]}
          >
            <AntInput placeholder="请输入模板标题" disabled={isViewMode} />
          </Form.Item>
          
          <Form.Item
            name="Keywords"
            label="关键词"
            rules={[
              { required: true, message: '请输入关键词' },
              { max: 200, message: '关键词长度不能超过200个字符' }
            ]}
          >
            <AntInput placeholder="请输入关键词，多个用逗号分隔" disabled={isViewMode} />
          </Form.Item>
          
          <Form.Item
            name="Typeid"
            label="模板类型"
            rules={[{ required: true, message: '请选择模板类型' }]}
          >
            <Select 
              placeholder="请选择模板类型" 
              disabled={isViewMode}
              showSearch
              optionFilterProp="children"
            >
              {templateTypes.map(type => (
                <Select.Option key={type.value} value={type.value}>
                  {type.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="State"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select 
              placeholder="请选择状态" 
              disabled={isViewMode}
            >
              {stateOptions.map(state => (
                <Select.Option key={state.value} value={state.value}>
                  {state.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="Content"
            label="模板内容"
            rules={[
              { required: true, message: '请输入模板内容' },
              { max: 2000, message: '内容长度不能超过2000个字符' }
            ]}
          >
            <AntInput.TextArea 
              rows={6} 
              placeholder="请输入模板内容" 
              disabled={isViewMode}
            />
          </Form.Item>
          
          <Form.Item
            name="Remark"
            label="备注"
            rules={[{ max: 500, message: '备注长度不能超过500个字符' }]}
          >
            <AntInput.TextArea 
              rows={3} 
              placeholder="请输入备注信息" 
              disabled={isViewMode}
            />
          </Form.Item>
          
          {isViewMode && currentTemplate && (
            <>
              <Form.Item label="创建时间">
                <AntInput 
                  value={dayjs(currentTemplate.Createtime).format('YYYY-MM-DD HH:mm')} 
                  disabled 
                />
              </Form.Item>
              
              <Form.Item label="更新时间">
                <AntInput 
                  value={dayjs(currentTemplate.Updatetime).format('YYYY-MM-DD HH:mm')} 
                  disabled 
                />
              </Form.Item>
            </>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default TemplateManagement;